package org.dg.dgimg.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dg.dgimg.utils.JWTUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Writer:DG
 * @Data:2024/6/7 10:13
 */

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean tip = false;
        //首先从Header中取出JWT
        String authorization = request.getHeader("Authorization");
        //判断是否包含JWT且格式正确
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            //开始解析成UserDetails对象，如果得到的是null说明解析失败，JWT有问题
            String UUID = JWTUtils.resolveJwt(token);
            if (UUID != null && !UUID.isEmpty()) {
                if (isValidToken(UUID)) {
                    tip = true;
                    // 将UUID存储在请求属性中
                    request.setAttribute("UUID", UUID);
                    /**
                     *      接下来的后续处理中获取到用户携带过来的UUID
                     *     @GetMapping("/some-endpoint")
                     *     public String handleRequest(HttpServletRequest request) {
                     *         // 从请求属性中获取UUID
                     *         String UUID = (String) request.getAttribute("UUID");
                     */
                }
            }

        }
        if (tip) return true;
        return returnFalse(response);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理完成后的处理
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的清理工作
    }

    private boolean isValidToken(String token) {
        // 实现token验证逻辑，根据实际业务需求进行实现
        // 这里可以添加你的逻辑来验证token
        Boolean hasToken = stringRedisTemplate.hasKey(token);
        // 如果token存在，继续处理请求
        return Boolean.TRUE.equals(hasToken);
        // 返回true表示token有效，返回false表示token无效
    }

    private boolean returnFalse(HttpServletResponse response) throws IOException {

        // 设置响应状态码为401未授权
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 设置响应内容类型为application/json
        response.setContentType("application/json;charset=UTF-8");

        // 构建错误信息
        Map<String, Object> errorData = new HashMap<>();
        errorData.put("status", "401");
        errorData.put("error", "未获取授权");

        // 将错误信息转换为JSON并写入响应
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(errorData);

        // 写入响应
        response.getWriter().write(jsonResponse);
        return false;
    }

}
